﻿using DevExpress.XtraEditors;
using Lamex.Base;
using Lamex.Common;
using Lamex.Interface;
using Lamex.Library;
using Lamex.mMES.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.mMES.UI
{
    public partial class frmMES_Kanban_Show : FrmBaseDataCollection
    {
        #region 初始化&&设置缓存值
        System.Timers.Timer t2 = null;
        System.Timers.Timer t3 = null;//30分钟后定时器
        System.Timers.Timer t4 = null;     
        SerialPort serialPort1 = new SerialPort();
        SerialPort serialPort2 = new SerialPort();
        SerialPort serialPort3 = new SerialPort();
        SerialPort serialPort4 = new SerialPort();
        SerialPort serialPort5 = new SerialPort();
        SerialPort serialPort6 = new SerialPort();
        SerialPort serialPort7 = new SerialPort();
        SerialPort serialPort8 = new SerialPort();
        string COM1 = "";
        string COM2 = "";
        string COM3 = "";
        string COM4 = "";
        string COM5 = "";
        string COM6 = "";
        string COM7 = "";
        string COM8 = "";
        static string strStarTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
        DataTable dtUI = Common.GetTable.GetTable_Scan_UI();
        DataTable dtWorkCode = new DataTable();//异常条码表             
        string firstTime = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00";
        string lastTime = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
        string UserName = "";
        string PortName_COM = "";
        int iBeForComSum = 0;
        int iAfterComSum = 0;
        int iStanderItime = 200;
        int maxStandertime = 220;
        int minStandertime = 180;
        int standertime = 200;
        int productTime = 212;
        double iCycletime = 200;
        double iLimitime = 0.1;
        DataTable dtShowHeader = null;
        string _StationName = "";
        bool IsPress;
        #endregion
        #region 初始化窗体
        public frmMES_Kanban_Show(string StationName,bool IsPress)
        {



            InitializeComponent();
        
            
            try
            {
                this.Load += new System.EventHandler(this.frmMES_Kanban_Presssing_Load);
                
                this.IsPress = IsPress;
                UserName = Lamex.Common.Loginer.CurrentUser.Account;
                _StationName = StationName;
                DataTable dt = BaseBuildSql.GetDataTableBySql("select * from [dbo].[HR_Process_CycleTime] where PRODUCT='" + txtPartBarCode.Text + "'");

                if (dt.Rows.Count != 0)
                {
                    iCycletime = double.Parse(dt.Rows[0]["CYCLETIME"].ToString());
                    maxStandertime = int.Parse((iCycletime + double.Parse(dt.Rows[0]["LIMIT_RATE"].ToString()) * double.Parse(dt.Rows[0]["CYCLETIME"].ToString())).ToString());
                    minStandertime = int.Parse((iCycletime - double.Parse(dt.Rows[0]["LIMIT_RATE"].ToString()) * double.Parse(dt.Rows[0]["CYCLETIME"].ToString())).ToString());

                    iStanderItime = int.Parse((iCycletime).ToString());
                    productTime = int.Parse(dt.Rows[0]["CHANGEOVER_TIME"].ToString());
                }


                if (Lamex.Common.Loginer.CurrentUser.Account.Contains("WS"))
                {

                    UserName = "WS_" + StationName;
                    dtShowHeader = BaseBuildSql.GetDataTableBySql(@"select * from HR_Station_Info where STATION_NAME='" + UserName + "' and  isnull(LOCATION_ORDER,'')!='' and LOCATION_NAME not in (select LOCATION_NAME from HR_Station_Info where   STATION_NAME='WS_P05'  and  (LOCATION_NAME='科文' or LOCATION_NAME='组长')) order by LOCATION_ORDER desc ");
                    RefreshList.InitLoadUI(UserName, axWindowsMediaPlayer1, progressBar, pcBottom, dtShowHeader, StationName, IsPress);
                }
                else
                {
                    txtPartBarCode.ReadOnly = true;
                    UserName = "WS_" + StationName;
                    dtShowHeader = BaseBuildSql.GetDataTableBySql(@"select * from HR_Station_Info where STATION_NAME='" + UserName + "' and  isnull(LOCATION_ORDER,'')!='' and LOCATION_NAME not in (select LOCATION_NAME from HR_Station_Info where   STATION_NAME='WS_P05'  and  (LOCATION_NAME='科文' or LOCATION_NAME='组长')) order by LOCATION_ORDER desc ");
                    RefreshList.InitLoadUI(UserName, axWindowsMediaPlayer1, progressBar, pcBottom, dtShowHeader, StationName, IsPress);
                    RefreshList.RefreshListUI(UserName, lb_Name1, lb_Name2, labelControl1, picTop1, picTop2, picTop3, dtShowHeader, pcBottom, pcMid_L, maxStandertime, minStandertime, standertime, productTime, iCycletime, txtPartBarCode.Text, IsPress);
                }
                this.Text = UserName;
                gc_pcTop_L.Text = UserName + "岗位或产品信息";
                RefreshList.IsPicVisible(pcBottom);//2020-1-17 by jack
                #region 获取网络状态
                Lamex.Common.IniFile ini_1 = new Lamex.Common.IniFile(Application.StartupPath + "\\config\\NetWork.ini");
                string isFlag = ini_1.IniReadValue("NetWork Configuration", "Isconnected").ToString();
                string dateTimes = ini_1.IniReadValue("NetWork Configuration", "DateTimes").ToString();
                if (isFlag == "flase")
                {
                    //写入数据库
                    Common.ScanRecordHelper.Insert("888", DateTime.Now.ToString("yyyyMMddHHmmssfff"), 0, 0, Convert.ToDateTime(dateTimes), "网络断开", "ALL", UserName, "");
                    Common.ScanRecordHelper.Insert("999", DateTime.Now.ToString("yyyyMMddHHmmssfff"), 0, 0, DateTime.Now, "网络恢复", "ALL", UserName, "");
                    //更改状态为true
                    ini_1.IniWriteValue("NetWork Configuration", "Isconnected", "true");
                }
                this.Resize += new System.EventHandler(this.frmMES_Kanban_Presssing_Resize);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message+"MAIN") ;
            }
            #endregion
        }
        #endregion
        #region 第一次加载
        private void frmMES_Kanban_Presssing_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理

            try
            {
                if (IsPress)
                    RefreshList.LoadPicPath(pcBottom, UserName, _StationName);//2020-1-17 by jack
                DataTable dtItme = BaseBuildSql.GetDataTableBySql(@" select a.* from  [dbo].[HR_Work_ShiftRec]  a 
                                join (select top 1* from  [HR_Station_Info]  where STATION_NAME='" + UserName + @"') b on b.DEPARTMENT=a.DEPARTMENT
                                where   a.EFFECTIVE_DATE<=  CONVERT(nvarchar(10),GETDATE(),120) and CONVERT(nvarchar(10),GETDATE(),120)<CONVERT(nvarchar(10), a. EXPIRY_DATE,120)
                            ");
                if (dtItme.Rows.Count == 0)
                {
                    XtraMessageBox.Show("没有排班人员！无法操作");
                    return;
                }
                if (!DesignMode)
                {
                    dtWorkCode = Common.GetDataTable.GetWork_Barcode();
                    InitCom();//开启COM扫描
                    GetLastLamp(); //读取扫描表最后一个条码
                }
            }
            catch(Exception ex)
            {
                XtraMessageBox.Show(ex.Message+"LOAD");
            }
        }
        #endregion
        #region 方法
        //获取最后一个条码
        public void GetLastLamp()
        {
            //得到不是撤销标识且不是MES_MG11111的最后两个条码
            DataTable dt_S08 = Common.GetDataTable.GetNoCancelNoMG_Top2(firstTime, UserName);
            if (dt_S08.Rows.Count > 0)
            {
                string Barcode = dt_S08.Rows[0]["BARCODE"].ToString();
                Common.LampHelper.ChargeLamp(Barcode, UserName, lb_Name1, lb_Name2, labelControl1, picTop1, picTop2, picTop3, lblInfo_4, lblStatus, LampGreen, lblInfo_1, lblInfo_2, lblInfo_3, timer1);             
            }
        }
 
        //清空控件值
        public void ClearControl()
        {
            Invoke(new Action(() =>
            {
                txtPartBarCode.Text = "";
                txtScanerQty.Text = "";
                //txtQty.Enabled = false;
            }));
        }
               
        //插入数据到扫描记录
        private void InsertRecord()
        {
            try
            {
                Common.LogicHelper.Logic_ReceiveData(dtUI, firstTime, lastTime, UserName, strStarTime, lblInfo_1, lblInfo_2, lblInfo_3, lblInfo_4, gcMid_B, gridView1);                          
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
            }
        }           
        private void IsPieVisible()
        {
            RefreshList.IsPieVisible(pcBottom);//2020-1-17 by jack
        }
        private void IsPicVisible()
        {
            RefreshList.IsPicVisible(pcBottom);//2020-1-17 by jack
        }    
        // 检测网络是否通
        public bool JCServerIP()
        {
            try
            {
                Lamex.Common.IniFile ini = new Lamex.Common.IniFile(Application.StartupPath + "\\config\\CSFramework3.ini");
                string serverDbIp = ini.IniReadValue("SQL Configuration", "SqlServer").ToString();//获取数据库IP
                Ping objPingSender = new Ping();
                PingOptions objPinOptions = new PingOptions();
                objPinOptions.DontFragment = true;
                string data = "";
                byte[] buffer = Encoding.UTF8.GetBytes(data);
                int intTimeout = 1000;
                PingReply objPinReply = objPingSender.Send(serverDbIp, intTimeout, buffer, objPinOptions);
                string strInfo = objPinReply.Status.ToString();
                if (strInfo == "Success")
                {
                    return true;
                }
                else
                {
                    //写入log
                    TraceHelper.GetInstance().Info("网络连接中断......", "出现异常");
                    //写入标识
                    Lamex.Common.IniFile ini_1 = new Lamex.Common.IniFile(Application.StartupPath + "\\config\\NetWork.ini");
                    ini_1.IniWriteValue("NetWork Configuration", "DateTimes", DateTime.Now.ToString());
                    ini_1.IniWriteValue("NetWork Configuration", "Isconnected", "flase");

                    return false;
                }
            }
            catch (Exception)
            {
                //写入log
                TraceHelper.GetInstance().Info("网络连接中断......", "出现异常");
                //写入标识
                Lamex.Common.IniFile ini_1 = new Lamex.Common.IniFile(Application.StartupPath + "\\config\\NetWork.ini");
                ini_1.IniWriteValue("NetWork Configuration", "DateTimes", DateTime.Now.ToString());
                ini_1.IniWriteValue("NetWork Configuration", "Isconnected", "flase");
                return false;
            }
        }    
        //private void SendMailerCheck(string Barcode)
        //{
        //    try
        //    {
        //        if (Common.MailHelper.SendExpMail(UserName, UserName, Barcode))
        //        {
        //            t3 = new System.Timers.Timer(5000 * 12 * 30);
        //            t3.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp3);
        //            t3.AutoReset = true;
        //            t3.Enabled = true;
        //            t3.Start();
        //        }
        //        else
        //        {
        //            if (Barcode.Substring(0, 3) == "MES")
        //            {
        //                if (t3 != null)
        //                    t3.Stop();
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        XtraMessageBox.Show(ex.Message + "126");
        //    }
        //}
        #endregion
        #region 事件
        public void Timer_TimesUp1(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (t4 != null)
                {
                    t4.Stop();
                    t4.Dispose();
                    t4 = null;
                }
                IsPicVisible();
                if (t2 == null)
                {
                    t2 = new System.Timers.Timer(5000 * 4);
                    t2.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp2);
                    t2.AutoReset = true;
                    t2.Enabled = true;
                    t2.Start();
                }

            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message + "123");
            }
        }
        public void Timer_TimesUp2(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (t2 != null)
                {
                    t2.Stop();
                    t2.Dispose();
                    t2 = null;
                }

                IsPieVisible();
                if (t4 == null)
                {
                    t4 = new System.Timers.Timer(5000 * 2);
                    t4.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp1);
                    t4.AutoReset = true;
                    t4.Enabled = true;
                    t4.Start();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "124");
            }
        }
        //public void Timer_TimesUp3(object sender, System.Timers.ElapsedEventArgs e)
        //{
        //    Common.MailHelper.AferSendExpMail(UserName, UserName, t3);
        //}
        //【扫描框】触发事件
        private void txtPartBarCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar == 13)
                {
                    DataTable dt = BaseBuildSql.GetDataTableBySql("select * from [dbo].[HR_Process_CycleTime] where PRODUCT='" + txtPartBarCode.Text + "'");

                    if (dt.Rows.Count != 0)
                    {
                        iCycletime = double.Parse(dt.Rows[0]["CYCLETIME"].ToString());
                        maxStandertime = int.Parse((iCycletime + (int)(double.Parse(dt.Rows[0]["LIMIT_RATE"].ToString()) * double.Parse(dt.Rows[0]["CYCLETIME"].ToString())) ).ToString());
                        minStandertime = int.Parse((iCycletime - (int)(double.Parse(dt.Rows[0]["LIMIT_RATE"].ToString()) * double.Parse(dt.Rows[0]["CYCLETIME"].ToString()))).ToString());

                        iStanderItime = int.Parse((iCycletime).ToString());
                        standertime = iStanderItime;
                        productTime = int.Parse(dt.Rows[0]["CHANGEOVER_TIME"].ToString());
                    }

                    string str_barcode = txtPartBarCode.Text.Trim().ToUpper();
                    string str_qty = txtScanerQty.Text.Trim();
                    string golbal_field = Common.LogicHelper.Logic_Scan(str_barcode, dtUI, str_qty, strStarTime, UserName, PortName_COM, firstTime, lastTime,
                        lb_Name1, lb_Name2, labelControl1, picTop1, picTop2, picTop3, lblInfo_4, lblStatus, LampGreen, lblInfo_1, lblInfo_2, lblInfo_3, timer1,
                        gcMid_B, gridView1, out  strStarTime);
                    //switch (golbal_field)
                    //{
                    //    case "special_1":
                    //        Common.LampHelper.ChargeLamp(str_barcode, UserName, lb_Name1, lb_Name2, labelControl1, picTop1, picTop2, picTop3, lblInfo_4, lblStatus, LampGreen, lblInfo_1, lblInfo_2, lblInfo_3, timer1);
                    //        Common.ShowHelper.GetDisplayInfo(dtUI, gcMid_B, gridView1);
                    //        Task.Run(() => SendMailerCheck(str_barcode));
                    //        InsertRecord();//接收回之前的数据
                    //        break;

                    //    case "special_2":
                    //        Common.LampHelper.ChargeLamp(str_barcode, UserName, lb_Name1, lb_Name2, labelControl1, picTop1, picTop2, picTop3, lblInfo_4, lblStatus, LampGreen, lblInfo_1, lblInfo_2, lblInfo_3, timer1);
                    //        Common.ShowHelper.GetDisplayInfo(dtUI, gcMid_B, gridView1);
                    //        Task.Run(() => SendMailerCheck(str_barcode));
                    //        break;
                    //}
                    ClearControl();
                    RefreshList.ShowProcessInvokeList(UserName, dtShowHeader, pcBottom, pcMid_L, maxStandertime, minStandertime, standertime, productTime, iCycletime, true);//2020-1-17 by jack
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }
        //定时器触发(30秒一次)
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                ////网络判断
                //if (!JCServerIP())
                //{
                //    Common.LampHelper. endTime(timer1);
                //    DevExpress.XtraEditors.XtraMessageBox.Show("网络连接已断开,请按如下步骤操作:\r\n 1、点击确定，关闭系统\r\n 2、恢复网络连接\r\n 3、重新登陆系统", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //    Environment.Exit(0);
                //    GC.Collect();
                //}
                firstTime = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00";
                lastTime = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
                InsertRecord();//接收按压数据                
                Timer_TimesUp(null, null);//初始化COM端口

                t4 = new System.Timers.Timer(5000 * 4);
                t4.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp1);
                t4.AutoReset = true;
                t4.Enabled = true;
                t4.Start();
                //加载展示数据
                RefreshList.ShowProcessInvokeList( UserName,  dtShowHeader,  pcBottom,  pcMid_L,  maxStandertime,  minStandertime,  standertime,  productTime,  iCycletime, IsPress);//2020-1-17 by jack
            }
            catch (Exception ex)
            {
               // MessageBox.Show(ex.Message+"123");
            }
        }     
        #endregion
        #region 窗体重置
        private void frmMES_Kanban_Presssing_Resize(object sender, EventArgs e)
        {
            RefreshList.ResizePanel(dtShowHeader, pcBottom);
        }
        #endregion
        #region 扫描COM实现
        public string[] GetRunCom()
        {
            string[] str = SerialPort.GetPortNames();
            return str;
        }
        public void InitCom()
        {
            string[] str = GetRunCom();
            iBeForComSum = str.Count();
            if (str == null)
            {
                return;
            }
            Lamex.Common.IniFile ini = new Lamex.Common.IniFile(Application.StartupPath + "\\config\\ComSetting.ini");
            COM1 = ini.IniReadValue("COM Configuration", "COM1");
            COM2 = ini.IniReadValue("COM Configuration", "COM2");
            COM3 = ini.IniReadValue("COM Configuration", "COM3");
            COM4 = ini.IniReadValue("COM Configuration", "COM4");
            COM5 = ini.IniReadValue("COM Configuration", "COM5");
            COM6 = ini.IniReadValue("COM Configuration", "COM6");
            COM7 = ini.IniReadValue("COM Configuration", "COM7");
            COM8 = ini.IniReadValue("COM Configuration", "COM8");
            //添加串口项目
            foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
            {
                //获取有多少个COM口
                if (s == COM1)
                {
                    serialPort1 = new SerialPort();
                    InstanceSerialPort(s, serialPort1);
                }
                else if (s == COM2)
                {
                    serialPort2 = new SerialPort();
                    InstanceSerialPort(s, serialPort2);
                }
                else if (s == COM3)
                {
                    serialPort3 = new SerialPort();
                    InstanceSerialPort(s, serialPort3);
                }
                else if (s == COM4)
                {
                    serialPort4 = new SerialPort();
                    InstanceSerialPort(s, serialPort4);
                }
                else if (s == COM5)
                {
                    serialPort5 = new SerialPort();
                    InstanceSerialPort(s, serialPort5);
                }
                else if (s == COM6)
                {
                    serialPort6 = new SerialPort();
                    InstanceSerialPort(s, serialPort6);
                }
                else if (s == COM7)
                {
                    serialPort7 = new SerialPort();
                    InstanceSerialPort(s, serialPort7);
                }
                else if (s == COM8)
                {
                    serialPort8 = new SerialPort();
                    InstanceSerialPort(s, serialPort8);
                }

            }
            //StartTime();
            //alterTime();
        }

        public void InitSingleCom(string PortName)
        {
            string[] str = GetRunCom();

            //添加串口项目
            foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
            {
                //获取有多少个COM口
                if (s == PortName)
                {
                    serialPort1 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort1);
                }
                else if (s == PortName)
                {
                    serialPort2 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort2);
                }
                else if (s == PortName)
                {
                    serialPort3 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort3);
                }
                else if (s == PortName)
                {
                    serialPort4 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort4);
                }
                else if (s == PortName)
                {
                    serialPort5 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort5);
                }
                else if (s == PortName)
                {
                    serialPort6 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort6);
                }
                else if (s == PortName)
                {
                    serialPort7 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort7);
                }
                else if (s == PortName)
                {
                    serialPort8 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort8);
                }

                System.Threading.Thread.Sleep(1000);

            }
        }
        /// <summary>
        /// 实例化串行端口资源
        /// </summary>
        public void InstanceSerialPort(string comName, SerialPort serialPort)
        {


            try
            {
                //实例化串行端口
                //SerialPort serialPort = new SerialPort();
                //端口名  注:因为使用的是USB转RS232 所以去设备管理器中查看一下虚拟com口的名字
                serialPort.PortName = comName;
                //波特率
                serialPort.BaudRate = 9600;
                //奇偶校验
                serialPort.Parity = Parity.None;
                //停止位
                serialPort.StopBits = StopBits.One;
                //数据位
                serialPort.DataBits = 8;
                //忽略null字节
                serialPort.DiscardNull = true;

                //接收事件
                serialPort.DataReceived += serialPort_DataReceived;
                //开启串口
                serialPort.Open();
                //alterTime();
            }
            catch (Exception ex)
            {
                //XtraMessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort serialPort = (SerialPort)sender;
            try
            {
                ReceiveData(serialPort);
            }
            catch (Exception ex)
            {
                //SetMessage(ex.Message, serialPort.PortName);
            }
        }

        public void ReceiveData(object serialPortobj)
        {
            SerialPort serialPort = (SerialPort)serialPortobj;
            try
            {
                //防止数据接收不完整 线程sleep(100)
                System.Threading.Thread.Sleep(100);

                string str = serialPort.ReadExisting();
                PortName_COM = serialPort.PortName;
                if (str == string.Empty)
                {
                    return;
                }
                else
                {
                    txtPartBarCode.Invoke(new Action(() => { txtPartBarCode.Text = str.Replace("\r", "").Trim(); txtPartBarCode.Focus(); SendKeys.Send("\r\n"); }));

                }
            }
            catch (Exception ex)
            {
                //SetMessage(ex.Message, serialPort.PortName);
            }
        }




        public void Timer_TimesUp(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (COM1 == serialPort1.PortName)
            {
                if (serialPort1.IsOpen != true)
                {
                    serialPort1.Close();
                    InitSingleCom(serialPort1.PortName);
                }
            }
            if (COM2 == serialPort2.PortName)
            {
                if (serialPort2.IsOpen != true)
                {
                    serialPort2.Close();
                    InitSingleCom(serialPort2.PortName);
                }
            }
            if (COM3 == serialPort3.PortName)
            {
                if (serialPort3.IsOpen != true)
                {
                    serialPort3.Close();
                    InitSingleCom(serialPort3.PortName);
                }
            }
            if (COM4 == serialPort4.PortName)
            {
                if (serialPort4.IsOpen != true)
                {
                    serialPort4.Close();
                    InitSingleCom(serialPort4.PortName);
                }

            }
            if (COM5 == serialPort5.PortName)
            {
                if (serialPort5.IsOpen != true)
                {
                    serialPort5.Close();
                    InitSingleCom(serialPort5.PortName);
                }
            }
            if (COM6 == serialPort6.PortName)
            {
                if (serialPort6.IsOpen != true)
                {
                    serialPort6.Close();
                    InitSingleCom(serialPort6.PortName);
                }
            }
            if (COM7 == serialPort7.PortName)
            {
                if (serialPort7.IsOpen != true)
                {
                    serialPort7.Close();
                    InitSingleCom(serialPort7.PortName);
                }
            }
            if (COM8 == serialPort8.PortName)
            {
                if (serialPort8.IsOpen != true)
                {
                    serialPort5.Close();
                    InitSingleCom(serialPort8.PortName);
                }
            }
        }

        public void CloseReceiveData()
        {
            serialPort1.Dispose();
            serialPort2.Dispose();
            serialPort3.Dispose();
            serialPort4.Dispose();
            serialPort5.Dispose();
            serialPort6.Dispose();
            serialPort7.Dispose();
            serialPort8.Dispose();
            serialPort1.Close();
            serialPort2.Close();
            serialPort3.Close();
            serialPort4.Close();
            serialPort5.Close();
            serialPort6.Close();
            serialPort7.Close();
            serialPort8.Close();
            if (t4 != null)
            {
                t4.Stop();
                t4.Dispose();
            }

            if (t2 != null)
            {
                t2.Stop();
                t2.Dispose();
            }
            if (t3 != null)
            {
                t3.Stop();
                t3.Dispose();
            }
        }
        #endregion
        #region 关闭窗体
        private void frmMES_Kanban_Presssing_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult.Yes == XtraMessageBox.Show("是否确定要关闭界面", "", MessageBoxButtons.YesNo))
            {
                CloseReceiveData();
                e.Cancel = false;
            }
            else
                e.Cancel = true;

        }
        #endregion
        #region 进度条
        private void ShowProductSumProgressBar()
        {
            //int iPass = 0;
            //DataTable dtPass = BaseBuildSql.GetDataTableBySql(@" select   sum(SCAN_QTY) SCAN_QTY,CONVERT(nvarchar(6),BARCODE) BARCODE from HR_Scan_Record  where CONVERT(nvarchar(6),BARCODE)='MES_QC' and CONVERT(nvarchar(10),SCAN_TIME,120)=CONVERT(nvarchar(10),GETDATE(),120)  group by CONVERT(nvarchar(6),BARCODE)
            //                    union all
            //                    select m.SCAN_QTY-n.SCAN_QTY SCAN_QTY,m.MES_PD from (select sum(SCAN_QTY) SCAN_QTY,'MES_PD' as MES_PD from HR_Scan_Record 
            //                    where LOCATION_CODE='WS_S08_09' and CONVERT(nvarchar(10),SCAN_TIME,120)=CONVERT(nvarchar(10),GETDATE(),120)
            //                    group by LOCATION_CODE) m 
            //                    left join (select   sum(SCAN_QTY) SCAN_QTY,CONVERT(nvarchar(6),BARCODE) BARCODE,'MES_PD' as MES_PD from HR_Scan_Record  where CONVERT(nvarchar(6),BARCODE)='MES_QC'  group by CONVERT(nvarchar(6),BARCODE)
            //                    ) n on n.MES_PD=m.MES_PD ");

            //DataRow dr = dtPass.Select(" 1=1 and BARCODE='MES_PD'").FirstOrDefault();
            //if (dr == null) iPass = 0;
            //else
            //    iPass = int.Parse(dr["SCAN_QTY"].ToString());
            progressBar.Visible = true;
            progressBar.Properties.Minimum = 0;
            progressBar.Properties.Maximum = 100;
            progressBar.Properties.Step = 10;
            progressBar.Properties.ProgressViewStyle = DevExpress.XtraEditors.Controls.ProgressViewStyle.Solid;
            progressBar.Position = 0;
            progressBar.Properties.ShowTitle = true;
            progressBar.Properties.PercentView = true;

            string startime = "2019-11-12 08:00:00";
            DateTime time = Convert.ToDateTime(startime);
            TimeSpan span = DateTime.Now.Subtract(time);
            progressBar.Position = span.Hours * 10;





        }

        #endregion
        #region  按钮
        //重置COM
        public override void DoResetCom(IButtonInfo sender)
        {
            InitCom();
            base.DoResetCom(sender);
        }
        #endregion
        #region 图表点击
        private void frmSeatControlUI1_DoubleClick(object sender, EventArgs e)
        {
            IsPieVisible();
        }        
        private void labelControl1_DoubleClick(object sender, EventArgs e)
        {
            picTop3.Visible = true;
            labelControl1.Visible = false;
        }
        private void picTop3_DoubleClick(object sender, EventArgs e)
        {
            picTop3.Visible = false;
            labelControl1.Visible = true;
        }
        #endregion

    }
}